package com.celesea.auth.group.service;

import com.celesea.auth.group.dao.GroupUserDao;
import com.celesea.auth.group.entity.Group;
import com.celesea.auth.group.entity.GroupUser;
import com.celesea.auth.group.vo.GroupVo;
import com.celesea.framework.service.AbstractBaseService;
import com.celesea.framework.util.CollectionKit;
import com.celesea.framework.util.EnvUtil;
import com.celesea.framework.vo.DictionaryVo;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author JackYuan
 * @create 2017-10-28 20:48
 */
@Service
public class GroupUserServiceImpl extends AbstractBaseService<GroupUser> implements GroupUserService {

    public static final String GROUP_ID = "groupId";
    @Autowired
    private GroupUserDao groupUserDao;

    @Override
    public List<GroupUser> findByGroup(String roleId) {
        return groupUserDao.selectByExample(buildExample(roleId));
    }

    @Override
    public int deleteByGroup(String roleId) {
        return groupUserDao.deleteByExample(buildExample(roleId));
    }

    @Override
    public int insertByGroup(GroupVo entity) {
        List<GroupUser> groupUsers = Lists.newArrayList();
        if (CollectionKit.isNotEmpty(entity.getUsers())) {
            groupUsers = entity.getUsers().stream().map(
                    item -> generatPk(new GroupUser(entity, item))
            ).collect(Collectors.toList());
        }
        if (CollectionKit.isNotEmpty(groupUsers)) {
            return groupUserDao.insertList(groupUsers);
        }
        return 0;
    }

    @Override
    public List<DictionaryVo> findByGroupCode(String code) {
        Group group =new Group();
        group.setCode(code);
        group.setTenantId(EnvUtil.getTenantId());
        return groupUserDao.findByGroupCode(group);
    }

    private Example buildExample(String roleId) {
        Example example = new Example(GroupUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(GROUP_ID, roleId);
        return example;
    }


}
